//
//  HGFile.m
//  HGMM
//
//  Created by @HUI on 15/9/21.
//  Copyright (c) 2015年 cc. All rights reserved.
//

#import "HGFile.h"
#import "HGPluginUtil.h"
#import "HGPluginViewController.h"
#import "UIView+ViewController.h"
#import "iCloudManager.h"
#import "NSDictionary+json.h"

typedef void(^BackBlock)(NSString *fileName,NSString *fileUrl);
typedef void(^BackAction)(NSString *error);



@interface HGFile ()<UIDocumentPickerDelegate, UIDocumentInteractionControllerDelegate>

//@property(nonatomic,strong)MPMoviePlayerViewController  *xmoviePlayer;
@property(nonatomic,copy)BackBlock block;



@property(nonatomic,copy)BackAction backAction;

@end

@implementation HGFile

-(void)createDir:(CDVInvokedUrlCommand *)command{
    __block CDVPluginResult *pluginResult = nil;
    if (command.arguments.count !=1 || ![command.arguments[0] isKindOfClass:[NSString class]]) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"args is wrong!"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        return ;
    }
    
    HGPluginViewController *vc;
    if ([self.viewController isKindOfClass:[HGPluginViewController class]]) {
        vc = (HGPluginViewController *)self.viewController;
        HGPluginUtil *util = [[HGPluginUtil alloc]init];
        NSString *rootPath = [NSString stringWithFormat:@"%@/files",[util getPluginDataDir:Plugin_IN]];
        NSString *filePath = [rootPath stringByAppendingPathComponent:command.arguments[0]];
        NSFileManager *manager = [NSFileManager defaultManager];
        if ([manager fileExistsAtPath:filePath]) {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"文件已存在!"];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
            return ;
        }
        NSError *error = nil;
        [manager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:&error];
        if (error) {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.localizedDescription];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
            return ;
        }
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"文件创建成功!"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        
    }
}

-(void)removeFile:(CDVInvokedUrlCommand *)command{
    __block CDVPluginResult *pluginResult = nil;
    if (command.arguments.count !=1 || ![command.arguments[0] isKindOfClass:[NSString class]]) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"args is wrong!"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        return ;
    }
    
    HGPluginViewController *vc;
    if ([self.viewController isKindOfClass:[HGPluginViewController class]]) {
        vc = (HGPluginViewController *)self.viewController;
        HGPluginUtil *util = [[HGPluginUtil alloc]init];
        NSString *rootPath = [NSString stringWithFormat:@"%@/files",[util getPluginDataDir:Plugin_IN]];
        NSString *filePath = [rootPath stringByAppendingPathComponent:command.arguments[0]];
        NSFileManager *manager = [NSFileManager defaultManager];
        if (![manager fileExistsAtPath:filePath]) {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"文件不存在!"];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
            return ;
        }
        NSError *error = nil;
        [manager removeItemAtPath:filePath error:&error];
        if (error) {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.localizedDescription];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
            return ;
        }
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"文件删除成功!"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }
}

-(void)renameFile:(CDVInvokedUrlCommand *)command{
    __block CDVPluginResult *pluginResult = nil;
    if (command.arguments.count !=2 || ![command.arguments[0] isKindOfClass:[NSString class]] || ![command.arguments[1] isKindOfClass:[NSString class]]) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"args is wrong!"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        return ;
    }
    
    HGPluginViewController *vc;
    if ([self.viewController isKindOfClass:[HGPluginViewController class]]) {
        vc = (HGPluginViewController *)self.viewController;
        HGPluginUtil *util = [[HGPluginUtil alloc]init];
        NSString *rootPath = [NSString stringWithFormat:@"%@/files",[util getPluginDataDir:Plugin_IN]];
        NSString *filePath = [rootPath stringByAppendingPathComponent:command.arguments[0]];
        NSString *renamePath = [rootPath stringByAppendingPathComponent:command.arguments[1]];
        NSFileManager *manager = [NSFileManager defaultManager];
        if (![manager fileExistsAtPath:filePath]) {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"文件不存在!"];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
            return ;
        }
        NSError *error = nil;
        [manager moveItemAtPath:filePath toPath:renamePath error:&error];
        if (error) {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.localizedDescription];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
            return ;
        }
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"文件重命名成功!"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }
}

-(void)getFileList:(CDVInvokedUrlCommand *)command{
    __block CDVPluginResult *pluginResult = nil;
    if (command.arguments.count !=1 || ![command.arguments[0] isKindOfClass:[NSString class]]) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"args is wrong!"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        return ;
    }
    
    HGPluginViewController *vc;
    if ([self.viewController isKindOfClass:[HGPluginViewController class]]) {
        vc = (HGPluginViewController *)self.viewController;
        HGPluginUtil *util = [[HGPluginUtil alloc]init];
        NSString *rootPath = [NSString stringWithFormat:@"%@/files",[util getPluginDataDir:Plugin_IN]];
        NSString *filePath = [rootPath stringByAppendingPathComponent:command.arguments[0]];
        NSFileManager *manager = [NSFileManager defaultManager];
        if (![manager fileExistsAtPath:filePath]) {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"文件不存在!"];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
            return ;
        }
        NSError *error = nil;
        NSArray *arr = [manager contentsOfDirectoryAtPath:filePath error:&error];
        if (error) {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.localizedDescription];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
            return ;
        }
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:arr];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }
}

-(void)getBase64File:(CDVInvokedUrlCommand *)command{
    __block CDVPluginResult *pluginResult = nil;
    if (command.arguments.count !=1 || ![command.arguments[0] isKindOfClass:[NSString class]]) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"args is wrong!"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        return ;
    }
    
    HGPluginViewController *vc;
    if ([self.viewController isKindOfClass:[HGPluginViewController class]]) {
        vc = (HGPluginViewController *)self.viewController;
        HGPluginUtil *util = [[HGPluginUtil alloc]init];
        //NSString *rootPath = [NSString stringWithFormat:@"%@/files",[util getPluginDataDir:vc.pluginId]];
        NSString *filePath = command.arguments[0]; //[rootPath stringByAppendingPathComponent:command.arguments[0]];
        NSFileManager *manager = [NSFileManager defaultManager];
        if (![manager fileExistsAtPath:filePath]) {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"文件不存在!"];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
            return ;
        }
        NSError *error = nil;
        NSData *data = [NSData dataWithContentsOfFile:filePath options:NSDataReadingUncached error:&error];
        if (error) {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.localizedDescription];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
            return ;
        }
        NSString *base64Str = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:base64Str];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }
}


/*
-(void)getLocalFile:(CDVInvokedUrlCommand *)command{
    
    __weak HGFile *weakself = self;
    
   
    
    self.block = ^(NSString *fileName, NSData *fileData) {
        
        NSString *base64Str = [fileData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        NSDictionary *dic = @{
                              fileName:base64Str
                              };
        
        NSString *resultString = [dic toReadableJSONString];
        
        
        CDVPluginResult* pluginResult = nil;
        
        
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:resultString];
        [weakself.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        
    };
    
    [self openfile];
}

-(void)openfile{
    
    NSArray *documentTypes = @[@"public.content", @"public.text", @"public.source-code ", @"public.image", @"public.audiovisual-content", @"com.adobe.pdf", @"com.apple.keynote.key", @"com.microsoft.word.doc", @"com.microsoft.excel.xls", @"com.microsoft.powerpoint.ppt"];
    
    UIDocumentPickerViewController *documentPickerViewController = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:documentTypes inMode:UIDocumentPickerModeOpen];
    documentPickerViewController.delegate = self;
    [self.webView.viewContoller presentViewController:documentPickerViewController animated:YES completion:nil];
    
}

#pragma mark - UIDocumentPickerDelegate
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url {
    
    NSArray *array = [[url absoluteString] componentsSeparatedByString:@"/"];
    NSString *fileName = [array lastObject];
    fileName = [fileName stringByRemovingPercentEncoding];
    
    if ([iCloudManager iCloudEnable]) {
        [iCloudManager downloadWithDocumentURL:url callBack:^(id obj) {
            NSData *data = obj;
            
            if (self.block) {
                
                self.block(fileName, data);
            }
            
        }];
    }
    
}
*/

-(void)getLocalFile:(CDVInvokedUrlCommand *)command{
    
    __weak HGFile *weakself = self;
    
    
    
    self.block = ^(NSString *fileName, NSString *fileUrl) {
        
        //         NSString *base64Str = [fileData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        NSDictionary *dic = @{
                              //fileName:base64Str
                              @"fileName":fileName,
                              @"fileUrl":fileUrl
                              
                              };
        
        NSString *resultString = [dic toReadableJSONString];
        
        
        CDVPluginResult* pluginResult = nil;
        
        
        
        // pluginResult = [CDVPluginResult resultWithStatus:(CDVCommandStatus_OK) messageAsDictionary:dic];
        
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:resultString];
        [weakself.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        
    };
    
    
    self.backAction = ^(NSString *error) {
        
        CDVPluginResult* pluginResult = nil;
        
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error];
        [weakself.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        
    };
    
    [self openfile];
}

-(void)openfile{
    
    NSArray *documentTypes = @[@"public.content", @"public.text", @"public.source-code ", @"public.image", @"public.audiovisual-content", @"com.adobe.pdf", @"com.apple.keynote.key", @"com.microsoft.word.doc", @"com.microsoft.excel.xls", @"com.microsoft.powerpoint.ppt"];
    
    UIDocumentPickerViewController *documentPickerViewController = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:documentTypes inMode:UIDocumentPickerModeOpen];
    documentPickerViewController.delegate = self;
    [self.webView.viewContoller presentViewController:documentPickerViewController animated:YES completion:nil];
    
}


#pragma mark - UIDocumentPickerDelegate
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url {
    
    NSArray *array = [[url absoluteString] componentsSeparatedByString:@"/"];
    NSString *fileName = [array lastObject];
    fileName = [fileName stringByRemovingPercentEncoding];
    
    if (fileName.length == 0) {
        
        /*
         UIAlertController *alerVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"您所选的文件格式不支持" preferredStyle:(UIAlertControllerStyleAlert)];
         [alerVC addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
         
         }]];
         
         [self.webView.viewContoller presentViewController:alerVC animated:YES completion:^{
         
         }];
         */
        
        if (self.backAction) {
            
            self.backAction(@"您所选的文件格式不支持");
        }
        
        return;
    }
    
    
    
    if ([iCloudManager iCloudEnable])
    {
        [iCloudManager downloadWithDocumentURL:url callBack:^(id obj) {
            //NSData *data = obj;
            
            NSData *data = obj;
            
           // HGPluginViewController *vc = (HGPluginViewController *)self.viewController;
        
            NSString *rootPath = [NSString stringWithFormat:@"%@/%@",NSHomeDirectory(),HGFilePath]; // [NSString stringWithFormat:@"%@/fileDoc",[util getPluginDataDir:vc.pluginId]];
            
            NSFileManager *manager = [NSFileManager defaultManager];
            if (![manager fileExistsAtPath:rootPath]) {
                [manager createDirectoryAtPath:rootPath withIntermediateDirectories:YES attributes:nil error:nil];
            }
            
            NSString *path = [NSString stringWithFormat:@"%@/%@",rootPath,fileName];
            
            
            [data writeToFile:path atomically:YES];
            
            if (self.block) {
                self.block(fileName,path);
            }
            
        }];
    }
    else
    {
        
        if (self.backAction) {
            
            self.backAction(@"您的iPhone设备没有打开iCloud功能,不支持附件选取");
        }
        
        
    }
    
    
    
}



@end
